#include "Color.h"

rgb::rgb()
:r(0),g(0),b(0)
{
}

rgb::rgb(unsigned char r_,unsigned char g_,unsigned char b_)
:r(r_),g(g_),b(b_)
{
}

rgb::rgb(unsigned int color)
:r((color>>16)&0x000000FF)
,g((color>>8)&0x000000FF)
,b(color&0x000000FF)
{
}


void rgb::hsl(unsigned char h,unsigned char s,unsigned char l)
{
	if(s==0)
	{
		r = l;
		g = l;
		b = l;
	}
	else
	{
		float fh = (float)h / 255.0f;
		float fs = (float)s / 255.0f;
		float fl = (float)l / 255.0f;

		float t1=0,t2=0;

		if(fs<0.5f)
		{
			t2 = fl * (1.0f + fs);
		}
		else
		{
			t2 = fl+fs - fl*fs;
		}

		t1 = 2.0f*fl - t2;

		float rt = fh + 1.0f / 3.0f;
		float gt = fh;
		float bt = fh - 1.0f / 3.0f;

		if(rt<0)
			rt += 1.0f;
		if(rt>1)
			rt -= 1.0f;

		if(gt<0)
			gt += 1.0f;
		if(gt>1)
			gt -= 1.0f;

		if(bt<0)
			bt += 1.0f;
		if(bt>1)
			bt -= 1.0f;
		//R
		if(6.0f*rt<1.0f)
			rt = t1 + (t2-t1)*6.0f*rt;
		else if(2.0f*rt<1.0f)
			rt = t2;
		else if(3.0f*rt<2.0f)
			rt = t1 + (t2-t1)*6.0f*((2.0f / 3.0f)-rt);
		else
			rt = t1;

		//G
		if(6.0f*gt<1.0f)
			gt = t1 + (t2-t1)*6.0f*gt;
		else if(2.0f*gt<1.0f)
			gt = t2;
		else if(3.0f*gt<2.0f)
			gt = t1 + (t2-t1)*6.0f*((2.0f / 3.0f)-gt);
		else
			gt = t1;

		//B
		if(6.0f*bt<1.0f)
			bt = t1 + (t2-t1)*6.0f*bt;
		else if(2.0f*bt<1.0f)
			bt = t2;
		else if(3.0f*bt<2.0f)
			bt = t1 + (t2-t1)*6.0f*((2.0f / 3.0f)-bt);
		else
			bt = t1;

		r = (unsigned char)(rt * 255.0f);
		g = (unsigned char)(gt * 255.0f);
		b = (unsigned char)(bt * 255.0f);
	}
}

unsigned int rgb::hsl()
{
	return 0;
}

rgb::operator unsigned int()
{
	return 255<<24 | r << 16 | g<<8 | b;
}

unsigned int hsl(unsigned char h,unsigned char s,unsigned char l)
{
	rgb temp;
	temp.hsl(h,s,l);
	return temp;
}